<?php

class DbTamer extends Controller {
    
	function setVars()
	{
		$this->tpl['title'] = "DB TaMeR";
		//$this->tpl['head'] = '';
        $this->tpl['body'] = '';
        $this->tpl['sidebar'] = FALSE;
        $this->seg->appl  = $this->uri->segment(1,'admin');
        $this->seg->classes = $this->uri->segment(2,'dbtamer');
        $this->seg->func  = $this->uri->segment(3,'viewgrit');
        $this->seg->table = $this->uri->segment(4,FALSE);
        $this->seg->field = $this->uri->segment(5,FALSE);
        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));
        define('GETURL',site_url(URI).'/');
	}
    
	function __construct() 
	{
		parent::Controller();
        $this->auth->CheckTaMeR(101,100);
		$this->setVars();
        //$this->load->library('profiler');
        $this->load->helper('inflector');
        //$this->load->library('validation');
        if($this->input->post('saveMeta')){
            $this->save();
        }
	}
    
	function index()
	{
        $this->gettable();
	}

    /**
     * @note	viewgrit
     * @info	Start Page
     * @author	Dennis T. Kaplan
     *
     * @access	public
     * @param	none
     * @return	Start Page  
     */	
    function viewgrit()
    {
        $this->gettable();
        $this->getfield();
        $this->grit();
        $this->loadView();
    }
    
    function addedit()
    {
        $this->load->model('data_model','dbtamer');

        # For Ajax
        $this->load->library('pquery');
        $this->tpl['controller_url'] = site_url($this->uri->segment(1).'/'.$this->uri->segment(2)).'/';
        $this->tpl['tpljs'][]  = 'ShowHideInputFields';
        
        if($this->input->post('field')){
            $this->dbtable = $this->input->post('table');
            $this->dbfield = $this->input->post('field');
        }
        
        $this->tpl['body'] .= '<h2>Database Meta Data</h2>';
        
        $dbMeta = $this->db->field_data($this->seg->table);
        
        foreach($dbMeta as $v){
            if($v->name == $this->seg->field){
                $dbMeta =  $v;
                $dbMeta->table = $this->seg->table;
                unset($dbMeta->primary_key);
                unset($dbMeta->max_length);
                $this->tpl['body'] .= form_open('admin/dbtamer/');
                $this->tpl['body'] .= '<dl>';
                foreach($v as $k=>$m){
                    $this->tpl['body'] .= "<dt>$k</dt>\n<dd>\n";
                        $this->tpl['body'] .=  form_input(array(
                            'name'        => $k,
                            'id'          => $k,
                            'value'       => $m,
                            'readonly'    => 'readonly'
                            )
                            );
                    $this->tpl['body'] .= "\n</dd>\n";
                }
                $this->tpl['body'] .= '</dl>';
                
                // ******************** Start Nested Set Meta Data *************
                $this->tpl['body'] .= '<h2>Database TaMeR Meta Data</h2>';
                
                $nt = $this->dbtamer->getTreePreOrder($this->dbtamer->getNodeFromId('160'));
                $nt = $nt['result_array'];
                $note = $nt[0];
                unset($nt[0]);
                
                
                foreach($nt as $k=>$v){
                    $options[$v['id']]=$v['name'];
                }
                $uri = site_url($this->uri->segment(1).'/'.$this->uri->segment(2)).'/';        
                $this->tpl['body'] .= '<form action="http://localhost/pzzazz.php/test/nsd/nsd_ajax" method="post">';
                $js=  $this->pquery->remote_function(array('update' => '#field', 'url' => $uri));
                $this->tpl['body'] .= form_dropdown("field",$options, FALSE, "onchange=change(this.value)").'<br />';
                foreach($nt as $k=>$v){
                    if($v['data']) {
                        $data[$v['id']]['id']= 'ShowHide';
                        $data[$v['id']]['name']= $v['id'];
                        $data[$v['id']]['value']=$v['data'];
                        if($v['name'] != 'validator_list'){
                            $data[$v['id']]['size']= '8';
                        }else{
                            $data[$v['id']]['size']= '80';
                        }
                    }
                }
                
                foreach($data as $k=>$v){
                    if ($v['name'] != 191){
                        $this->tpl['body'] .= form_input($v);
                    }else{
                        unset($v['size']);
                        
                        $v['value'] = str_replace ('|', "\n", $v['value'], $count);
                        $a= array("rows"=>14, "cols"=>25);
                        $a = array_merge($a,$v);
                        $this->tpl['body'] .= form_textarea($a);
                    }
                }
                $this->tpl['body'] .= form_submit('saveMeta', 'Save Meta Data');
                $this->tpl['body'] .= '</form>';
                $this->tpl['body'] .= '<br />';
                // ********************  End Nested Set Meta Data **************

                $fieldMeta = $this->get_field_meta_data();
                //printa($fieldMeta);
                /*
                [meta_id] => 1
                [meta_table] => 1
                [meta_field] => agenda_id
                [meta_dump] => a:20:{s:4:"name";s:1:"0";s:4:"type";s:
                    */
                    if($fieldMeta !== FALSE){
                        foreach($fieldMeta as $k=>$v){
                            $this->tpl['body'] .= "<dt>$k</dt>\n<dd>\n";
                            $this->tpl['body'] .=  $v;
                            $this->tpl['body'] .= "\n</dd>\n";
                            
                        }
                }
                
            }
        }
        $this->loadView();
    }
    
   	function unsettable()
	{
        $this->session->set_userdata(array('dbtable' => false,'dbfield' => false));
        $this->session->set_userdata(array('dbfield' => ''));
        redirect('admin/dbtamer/', 'location');
	}
    
    private function get_field_meta_data()
    {
        if(!$this->seg->table || !$this->seg->field) return FALSE;
        $table = 'admin_metas';
        $where = array('meta_table' => $this->seg->table,'meta_field' => $this->seg->field);
        $this->db->where($where);
        $this->db->limit(1);
        $query = $this->db->get($table);
        if ($query->num_rows() > 0)
        {
            $fieldMeta = $query->row();
            printa($fieldMeta);
            /*
            [meta_id] => 1
            [meta_table] => 1
            [meta_field] => agenda_id
            [meta_dump] => a:20:{s:4:"name";s:1:"0";s:4:"type";s:
                */
                if($fieldMeta !== FALSE){
                    return unserialize($fieldMeta->meta_dump);
                }
                return FALSE;
        }
    }
    
    
    private function grit()
    {
        
        if(!$this->dbtable) return FALSE;
        $table = 'admin_metas';
        $this->db->where('meta_table', $this->dbtable);
        $query = $this->db->get($table);
        if ($query->num_rows() > 0)
        {
            foreach($query->result_array() as $s):
            $tbresult[] = unserialize($s['meta_dump']);
            endforeach;
            $this->table->set_template($this->table->table_tmpl());
            $this->table->set_heading(array_keys($tbresult[0]));
            //unset($tbresult[0]);
            foreach($tbresult as $k=>$row):
            $row = (object) $row;
            $tbresult[$k]['name'] = anchor(GETURL. 'addedit/'.$row->table.'/'. $row->name,$row->name);
            $this->table->add_row($tbresult[$k]);
            endforeach;            
            echo $this->table->generate();
            $this->table->clear();
        }else{
            echo '<h4>Select field then click "Set New/Reset DB Field"</h4>';
        }
        return;
    }
    
    
    private function save()
	{
        $table = 'admin_metas';
        $where = array(
            'meta_table'    => $this->dbtable,
            'meta_field'    => $this->dbfield
            );
        unset($_POST['saveMeta']);
        $data = array(
            'meta_table'    => $this->dbtable,
            'meta_field'    => $this->dbfield,
            'meta_dump'     => serialize($_POST)
            );
        $query = $this->db->getwhere($table, $where, 1);
        if ($query->num_rows() > 0){
            $this->db->update($table, $data, $where); 
        }else{
            $this->db->insert($table, $data);
        }
	}
    
    /* Providing select box to get the table */

	private function gettable()
	{
        $this->load->library('Pquery');
        foreach($this->db->list_tables() as $v){
            $dbtables[$v] = $v;
        }
        $this->load->library('pquery');
        $b = $this->pquery->form_remote_tag(array('url'=>GETURL.'getfield/','update'=>'#fieldid','type'=>'POST'));
        $b .= form_dropdown('table', $dbtables, 'Tables');
        $b .= form_submit('get_db_field', 'Set DB Table').anchor('admin/dbtamer/unsettable/', 'Unset Table');
        $b .= '</form>';
        $b .= '<div id="fieldid"></div>';
        $this->tpl['body'] .= $b;
        $this->loadView();
        //return;
	}
    
    /* Providing select box to get the field */
    function getfield()
    {
        if($this->input->post('table')){
            $this->dbtable = $this->input->post('table');
        }elseif(!$this->dbtable){
            return FALSE;
        }
        foreach($this->db->list_fields($this->dbtable) as $v){
            $fields[$v] = $v;
        }
        unset($fields[0]);
        $t = humanize($this->dbtable);
        $this->load->library('pquery');
        echo $this->pquery->form_remote_tag(array('url'=>GETURL.'addedit/','update'=>'#fieldid','type'=>'POST'));
        echo form_dropdown('field', $fields);
        echo form_submit('get_db_field', 'Set New DB Field');
        echo form_hidden('table', $this->dbtable);
        echo '</form>';
        $this->grit();
        return;
    }
    
    
	private function loadView()
	{
        //echo $this->tpl['body'];
        //printa($this->session->userdata());
		$this->load->view('blank',$this->tpl);
	}
    
}
?>
